package com.zh.kotlin_mvvm.ui

import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.view.View
import androidx.core.content.FileProvider
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.PermissionUtils
import com.zh.common.base.BaseActivity
import com.zh.common.ktx.loadUrl
import com.zh.common.ktx.setResult
import com.zh.common.ktx.toast
import com.zh.config.fragment.PictureFragment
import com.zh.kotlin_mvvm.databinding.ActivityPictureBinding
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date

class PictureActivity : BaseActivity<ActivityPictureBinding>() {

    private lateinit var pictureFragment: PictureFragment
    private val BACK_CAMERA = 10901
    private var imageUri: Uri? = null

    override fun initView(savedInstanceState: Bundle?) {
        pictureFragment = supportFragmentManager.findFragmentByTag("pictureF") as PictureFragment

        viewBinding.button9.setOnClickListener {
            pictureFragment.showSelectDialog()
        }
        intent?.getStringExtra("name")?.toast()
    }

    fun takePhoto(view: View) {
        PermissionUtils.permission(
            android.Manifest.permission.CAMERA,
            android.Manifest.permission.READ_EXTERNAL_STORAGE,
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE
        ).callback { isAllGranted, granted, deniedForever, denied ->
            if (isAllGranted) {
                val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) //打开相机的Intent
                if (intent.resolveActivity(this.packageManager) != null) { //这句作用是如果没有相机则该应用不会闪退，要是不加这句则当系统没有相机应用的时候该应用会闪退
                    //创建用来保存照片的文件
                    createImageFile()?.let {
                        imageUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            FileProvider.getUriForFile(
                                this, "${this.packageName}.fileprovider", it
                            )
                        } else {
                            Uri.fromFile(it)
                        }
                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri) //将用于输出的文件Uri传递给相机
                        startActivityForResult(intent, BACK_CAMERA) //打开相机
                    }
                }
            }
        }.request()
    }

    /**
     * 创建用来存储图片的文件，以时间来命名就不会产生命名冲突
     * @return 创建的图片文件
     */
    private fun createImageFile(): File? {
        val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
        val imageFileName = "JPEG_" + timeStamp + "_"
        val storageDir: File? = this.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        var imageFile: File? = null
        try {
            imageFile = File.createTempFile(imageFileName, ".jpg", storageDir)
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return imageFile
    }

    private fun Uri?.getRealPath(): String {
        this?.let {
            return "${getExternalFilesDir(Environment.DIRECTORY_PICTURES)}/${it.lastPathSegment}"
        }
        return ""
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        LogUtils.e(imageUri?.getRealPath())
        viewBinding.ivTake.loadUrl(imageUri?.getRealPath().toString())
    }

    override fun finish() {
        setResult {
            putExtra("name", "图片返回")
        }
        super.finish()
    }
}